package com.hanter.android.radui.mvp;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.fragment.app.FragmentManager;

import android.util.Log;

import com.hanter.android.radui.dialog.LoadingDialog;

public class LoadingDialogHelper {

    private static final String TAG = LoadingDialogHelper.class.getSimpleName();

    private static final int SHOW_DIALOG_DELAY = 250; // 250MS
    private static final int MSG_SHOW_PROGRESS = 1;
    private static final int MSG_DISMISS_PROGRESS = 2;
    private final FragmentManager fragmentManager;
    private LoadingDialog loadingDialog;
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_SHOW_PROGRESS:
                    Log.d(TAG, "on message: MSG_SHOW_PROGRESS");
                    showProgressDialogImmediately();
                    break;

                case MSG_DISMISS_PROGRESS:
                    Log.d(TAG, "on message: MSG_DISMISS_PROGRESS");
                    disProgressDialogImmediately();
                    break;
            }
        }
    };

    public LoadingDialogHelper(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    public void onDestroy() {
        dismissProgressDialog();
    }

    public void showProgressDialog() {
        Log.d(TAG, "send message: MSG_SHOW_PROGRESS");
        Message msg = handler.obtainMessage(MSG_SHOW_PROGRESS);
        handler.sendMessageDelayed(msg, SHOW_DIALOG_DELAY);
    }

    public void dismissProgressDialog() {
        Log.d(TAG, "remove message: MSG_SHOW_PROGRESS");
        Log.d(TAG, "send message: MSG_DISMISS_PROGRESS");
        handler.removeMessages(MSG_SHOW_PROGRESS);
        handler.obtainMessage(MSG_DISMISS_PROGRESS).sendToTarget();
    }

    private void showProgressDialogImmediately() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.newInstance();
            loadingDialog.show(fragmentManager, BaseView.TAG_LOADING_DIALOG);
        }
    }

    private void disProgressDialogImmediately() {
        if (loadingDialog != null) {
            loadingDialog.dismissAllowingStateLoss();
            loadingDialog = null;
        }
    }

}
